<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" wrapClassName="modal-add"
    destroyOnClose width="80%">
    <BasicForm @register="register" class="top-search" />
    <a-card class="common-card flex card-box" v-loading="loading" :title="treeRootData?.description">
      <!-- <template #extra>
        <a-input-search v-model:value="searchValue" placeholder="请输入" @search="getTableData" />
      </template> -->
      <a-tabs v-model:activeKey="currentTab" type="card" class="tab-content">
        <a-tab-pane v-for="item in tabList" :key="item.classifyId" :tab="item.classifyName">
        </a-tab-pane>
      </a-tabs>
      <BasicTable @register="registerTable" class="table-box"></BasicTable>
    </a-card>
  </BasicModal>
</template>
<script lang="ts"
  setup>
  import { ref, computed, unref, watch } from 'vue'
  import { BasicModal, useModalInner } from '@/components/Modal'
  import { getClassifyByPatent } from '@/api/collection/classify'
  import { BasicTable, useTable } from '@/components/Table'

  import { addBudgetRecord } from '@/api/sys/budgetData'
  import { message } from 'ant-design-vue'
  import { getDictListByCodeAndName } from '@/api/sys/dict'
  import { BasicForm, useForm } from '@/components/Form'
  import { modalFormSchema, modalColumns } from './data'
  import { TableItem } from '@/api/sys/model/budgetData'
  import dayjs from 'dayjs'

  defineOptions({ name: 'ModalAddRecord' })

  const emit = defineEmits(['success', 'register'])

  const isUpdate = ref(false)

  const tabList = ref<TableItem[]>([])
  const treeRootData = ref()
  const searchValue = ref()
  const currentTab = ref()
  const loading = ref(false)
  const selectedRowsData = ref<any[]>([])
  const dataSource = ref([])

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    getTabData()
  })
  const [register, { validate }] = useForm({
    schemas: modalFormSchema,
    showActionButtonGroup: false,
    labelWidth: 80,
  })

  const getTitle = computed(() => (!unref(isUpdate) ? '新增预算' : '修改预算'))
  const [registerTable, { clearSelectedRowKeys, setLoading }] = useTable({
    canResize: true,
    rowKey: 'classifyId',
    columns: modalColumns,
    pagination: false,
    dataSource,
    bordered: true,
    striped: false,
    rowSelection: {
      onChange: (selectedKeys, selectedData) => {
        selectedRowsData.value = selectedData
      },
    },
  })

  watch(
    () => currentTab.value,
    () => {
      getTableData()
      clearSelectedRowKeys()
      // selectedRowsData.value = []
    },
  )

  const getTabData = async () => {
    try {
      loading.value = true
      const parentData = await getDictListByCodeAndName({
        code: 'budget_manage',
        itemName: 'tree_id',
      })
      loading.value = false
      treeRootData.value = parentData
      const data = await getClassifyByPatent({ parentClassifyId: parentData.itemCode })
      currentTab.value = data[0]?.classifyId
      tabList.value = data
    } catch (error) {
      message.error(error)
    }
  }

  const getTableData = async () => {
    setLoading(true)
    const data = await getClassifyByPatent({
      parentClassifyId: currentTab.value,
      searchVal: searchValue.value,
    })
    setLoading(false)
    dataSource.value = data
  }

  async function handleSubmit() {
    try {
      const values = await validate()
      if (!selectedRowsData.value.length) {
        message.warn('请选择标签')
        return
      }
      const currentTabName = tabList.value.find(item => item.classifyId === currentTab.value)?.classifyName
      const data = selectedRowsData.value.map((item) => ({
        classifyId: item.classifyId,
        tag: currentTabName + '-' + item.classifyName,
        ...values,
        budgetYear: dayjs(values.budgetYear).format('YYYY'),
      }))

      setModalProps({ confirmLoading: true })
      addBudgetRecord(data).then((res) => {
        message.success(isUpdate.value ? '修改成功' : '添加成功')
        closeModal()
        emit('success', { isUpdate: unref(isUpdate), data })
      })
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>

<style scoped
  lang="scss">
  .card-box {

    :deep(.ant-card-head),
    :deep(.ant-card-body) {
      padding: 0;
    }
  }

  .top-search {
    padding: 8px;
    border: 1px solid #dcdee0;
    background: #f2f5f8;

    :deep(.ant-form-item) {
      margin: 0;
    }
  }

  .tab-content {
    margin-top: 8px;

    :deep(.ant-tabs-nav) {
      margin: 0;
      border: 1px solid #DBDEE3;
      border-bottom: none;
      border-left: none;
      background: #F3F7FB;

      .ant-tabs-nav-wrap {
        .ant-tabs-tab {
          width: 100px;
          height: 32px;
          margin-left: 0;
          border-left: 1px solid #DBDEE3;
          border-radius: 0;
          background: #F3F7FB;
          color: #333;
          font-size: 13px;
          font-weight: 700;

          &.ant-tabs-tab-active {
            background: #F3F7FB;
            color: #0067CC;
          }

          .ant-tabs-tab-btn {
            margin: 0 auto;
          }
        }
      }
    }
  }

  .table-box {
    :deep(.ant-table-wrapper) {
      padding: 0;
    }
  }
</style>
